import { useState } from 'react'
import type { Node } from 'reactflow'
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Space,
  Divider,
  Typography,
  List,
  Modal,
  Message,
} from '@arco-design/web-react'
import {
  IconClose,
  IconPlus,
  IconDelete,
  IconEdit,
} from '@arco-design/web-react/icon'
import type { Step } from '@/types'
import StepFormModal from './StepFormModal'
import './StepConfigPanel.css'

const { Title, Text } = Typography
const FormItem = Form.Item
const Option = Select.Option

interface StepConfigPanelProps {
  node: Node
  onUpdate: (node: Node) => void
  onClose: () => void
}

export default function StepConfigPanel({
  node,
  onUpdate,
  onClose,
}: StepConfigPanelProps) {
  const [form] = Form.useForm()
  const [stepModalVisible, setStepModalVisible] = useState(false)
  const [editingStep, setEditingStep] = useState<Step | null>(null)
  const [editingStepIndex, setEditingStepIndex] = useState<number>(-1)

  const steps: Step[] = node.data.steps || []

  // 更新 Stage 信息
  const handleStageUpdate = (values: any) => {
    const updatedNode = {
      ...node,
      data: {
        ...node.data,
        ...values,
      },
    }
    onUpdate(updatedNode)
    Message.success('Stage 信息已更新')
  }

  // 添加 Step
  const handleAddStep = (step: Step) => {
    const newSteps = [...steps, { ...step, order: steps.length }]
    const updatedNode = {
      ...node,
      data: {
        ...node.data,
        steps: newSteps,
      },
    }
    onUpdate(updatedNode)
    setStepModalVisible(false)
    Message.success('Step 已添加')
  }

  // 编辑 Step
  const handleEditStep = (step: Step) => {
    const newSteps = [...steps]
    newSteps[editingStepIndex] = { ...step, order: editingStepIndex }
    const updatedNode = {
      ...node,
      data: {
        ...node.data,
        steps: newSteps,
      },
    }
    onUpdate(updatedNode)
    setStepModalVisible(false)
    setEditingStep(null)
    setEditingStepIndex(-1)
    Message.success('Step 已更新')
  }

  // 删除 Step
  const handleDeleteStep = (index: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个步骤吗？',
      onOk: () => {
        const newSteps = steps.filter((_, i) => i !== index)
        const updatedNode = {
          ...node,
          data: {
            ...node.data,
            steps: newSteps,
          },
        }
        onUpdate(updatedNode)
        Message.success('Step 已删除')
      },
    })
  }

  return (
    <div className="step-config-panel">
      <div className="panel-header">
        <Title heading={6} style={{ margin: 0 }}>
          配置 Stage
        </Title>
        <Button
          type="text"
          size="small"
          icon={<IconClose />}
          onClick={onClose}
        />
      </div>

      <div className="panel-content">
        {/* Stage 基本信息 */}
        <Card title="Stage 信息" bordered={false} size="small">
          <Form
            form={form}
            layout="vertical"
            initialValues={{
              name: node.data.name,
              executionMode: node.data.executionMode,
            }}
            onValuesChange={(_, allValues) => {
              handleStageUpdate(allValues)
            }}
          >
            <FormItem label="Stage 名称" field="name" rules={[{ required: true }]}>
              <Input placeholder="请输入 Stage 名称" />
            </FormItem>

            <FormItem label="执行模式" field="executionMode">
              <Select>
                <Option value={0}>串行执行</Option>
                <Option value={1}>并行执行</Option>
              </Select>
            </FormItem>
          </Form>
        </Card>

        <Divider />

        {/* Steps 列表 */}
        <Card
          title="Steps"
          bordered={false}
          size="small"
          extra={
            <Button
              type="primary"
              size="mini"
              icon={<IconPlus />}
              onClick={() => {
                setEditingStep(null)
                setEditingStepIndex(-1)
                setStepModalVisible(true)
              }}
            >
              添加 Step
            </Button>
          }
        >
          {steps.length === 0 ? (
            <div className="empty-steps">
              <Text type="secondary">暂无步骤，点击上方按钮添加</Text>
            </div>
          ) : (
            <List
              size="small"
              dataSource={steps}
              render={(step, index) => (
                <List.Item
                  key={index}
                  actions={[
                    <Button
                      type="text"
                      size="mini"
                      icon={<IconEdit />}
                      onClick={() => {
                        setEditingStep(step)
                        setEditingStepIndex(index)
                        setStepModalVisible(true)
                      }}
                    />,
                    <Button
                      type="text"
                      size="mini"
                      status="danger"
                      icon={<IconDelete />}
                      onClick={() => handleDeleteStep(index)}
                    />,
                  ]}
                >
                  <Space direction="vertical" size="mini" style={{ width: '100%' }}>
                    <Text bold>{step.name}</Text>
                    <Text type="secondary" style={{ fontSize: 11 }}>
                      类型: {getStepTypeName(step.stepType)}
                    </Text>
                  </Space>
                </List.Item>
              )}
            />
          )}
        </Card>
      </div>

      {/* Step 表单模态框 */}
      <StepFormModal
        visible={stepModalVisible}
        step={editingStep}
        onSubmit={editingStep ? handleEditStep : handleAddStep}
        onCancel={() => {
          setStepModalVisible(false)
          setEditingStep(null)
          setEditingStepIndex(-1)
        }}
      />
    </div>
  )
}

// 获取 Step 类型名称
function getStepTypeName(stepType: number): string {
  const typeMap: Record<number, string> = {
    1: 'Git Clone',
    2: 'Build',
    3: 'Test',
    4: 'Deploy',
    5: 'Docker Build',
    6: 'Docker Push',
    7: 'K8s Deploy',
    8: 'NuGet Push',
    9: 'Maven Deploy',
    10: 'Custom Script',
  }
  return typeMap[stepType] || '未知类型'
}
